package com.david.scan

import android.app.Activity
import android.app.Dialog
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.TextView
import android.widget.Toast


class CodeResultDialog(private var content: String, activity: Activity,  themeResId: Int): Dialog(activity, themeResId) {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))

        setContentView(R.layout.dialog_code_reault)

        // 获取window
        val window: Window? = window
        if (window != null) {
            // 设置dialog在底部显示
            window.setGravity(Gravity.BOTTOM)
            // 设置宽度全屏
            val layoutParams = window.attributes
            layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT
            window.attributes = layoutParams
        }


        findViewById<TextView>(R.id.dialog_result_content).text = content

        findViewById<View>(R.id.dialog_result_back).setOnClickListener {
            dismiss()
        }

        findViewById<View>(R.id.dialog_result_copy).setOnClickListener {
            // 获取ClipboardManager服务
            val clipboard: ClipboardManager? = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager?

            // 创建一个ClipData对象
            val clip = ClipData.newPlainText("", content)

            // 将ClipData内容放到系统剪贴板里。
            clipboard?.setPrimaryClip(clip)

            Toast.makeText(context, "复制成功", Toast.LENGTH_LONG).show()
        }

        //if (content.startsWith("http://") || content.startsWith("https://")) {
        val index = content.indexOf("://")
        if (index in 1..7) {
            findViewById<View>(R.id.dialog_result_navweb).let {
                it.setOnClickListener {
                    val uri = Uri.parse(content)
                    val intent = Intent(Intent.ACTION_VIEW, uri)
                    context.startActivity(intent)
                }

                it.visibility = View.VISIBLE
            }
        }
    }
}